<!DOCTYPE html>
<html lang="zh-CN" id="html">

<head>
  <title>电子课表</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/scheduleConfig.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
  <div class="globalContainer" id="globalContainer">
    <div class="classContainer background" id="classContainer" style="position: relative;"> <!-- 添加 position: relative -->
      <div class="class">加</div>
      <div class="class">载</div>
      <div class="class">中</div>
    </div>
    
    <!-- 修改 countdownContainer 的位置 -->
    <div class="countdownContainer" id="countdownContainer" style="display: block; position: absolute; left: 100%; top: 0;">
      <div class="countdowner" id="countdowner">
        <div class="currentClass" id="currentFullName">Loading</div>
        <div class="countdown" id="countdownText">00:00</div>
      </div>
    </div>
    
    <div class="leftSidebar sidebar background" id="leftSidebar"><span id="weekEN" class="t">Load</span><div class="corner options notIgnoreClick" id="weekCH">ing</div></div>
    <div class="rightSidebar sidebar background" id="rightSidebar"><span id="countdownDays" class="t">000</span><div class="corner">天</div></div>
  </div>
  <div class="miniCountdown" id="miniCountdown">00:00</div>
  <div class="nextClassHint" id="nextClassHint" style="display: none; position: fixed; top: var(--top-space); border-radius: var(--global-border-radius); background-color: rgba(0, 0, 0, var(--global-bg-opacity)); padding: var(--countdown-bg-padding); font-size: var(--countdown-font-size); font-family: JETB; color: #FFF; margin-left: 0px;"></div>
      </div>

</body>


<script>
  const { ipcRenderer } = require('electron');
  let scheduleData = getScheduleData();
  let globalContainer = document.getElementById('globalContainer')
  let classContainer = document.getElementById('classContainer')
  let countdownContainer = document.getElementById('countdownContainer')
  let countdowner = document.getElementById('countdowner')
  let currentFullName = document.getElementById('currentFullName')
  let countdownText = document.getElementById('countdownText')
  let weekEN = document.getElementById('weekEN')
  let weekCH = document.getElementById('weekCH')
  let countdownDays = document.getElementById('countdownDays')
  let miniCountdown = document.getElementById('miniCountdown')
  let rightSidebar = document.getElementById('rightSidebar')
  let leftSidebar = document.getElementById('leftSidebar')
  let root = document.querySelector(':root');
  let isClassCountdown = true
  let isClassHidden = true
  let lastScheduleData = {
    currentHighlight: {
      index: null,
      type: null,
      fullName: null,
      countdown: null,
      countdownText: null
    },
    scheduleArray: [null, null, null],
    timetable: null,
    divider: [null, null]
  }
  
let nextClassHint = document.getElementById('nextClassHint');
let isHintShown = false; // 标记提示是否已显示
let hintTimer = null; // 用于清除提示的定时器



  function setScheduleClass() {
    let classHtml = '';
    for (let i = 0; i < scheduleData.scheduleArray.length; i++) {
      let inner = scheduleData.scheduleArray[i]
      if (scheduleData.scheduleArray[i].indexOf('@') != -1) {
        inner = `<div><div style="display:inline">${inner.split('@')[0]}</div><div class="subClass">${inner.split('@')[1]}</div></div>`
      }
      if (scheduleData.currentHighlight.index == i) {
        if (scheduleData.currentHighlight.type === 'current')
          classHtml += `<div class="class current" id="highlighted">${inner}</div>`
        else if (scheduleData.currentHighlight.type === 'upcoming')
          classHtml += `<div class="class upcoming" id="highlighted">${inner}</div>`
      }
      else {
        if (scheduleData.currentHighlight.index > i)
          classHtml += `<div class="class" style="color:rgba(166,166,166);">${inner}</div>`
        else
          classHtml += `<div class="class">${inner}</div>`
      }
      if (scheduleData.divider.indexOf(i) != -1)
        classHtml += '<div class="divider"></div>'
    }
    classContainer.innerHTML = classHtml
  }

  function setBackgroundDisplay() {
    let elements = document.getElementsByClassName('background')
    for (element of elements) {
      element.style.visibility = (scheduleData.currentHighlight.type === 'current' && isClassHidden) ? 'hidden' : 'visible'
    }
  }

  function setCountdownerContent() {
    currentFullName.innerText = scheduleData.currentHighlight.fullName;
    currentFullName.style.color = scheduleData.currentHighlight.type === 'current' ? 'rgba(0, 255, 10, 1)' : 'rgba(255, 255, 5, 1)'
    countdownText.innerText = scheduleData.currentHighlight.countdownText;

        // 核心：检查是否距离下课还有10分钟（600秒）
    if (scheduleData.currentHighlight.type === 'current' && scheduleData.currentHighlight.countdown === 600 && !isHintShown) {
        const nextClass = getNextClassInfo();
        if (nextClass) {
            // 显示提示
          nextClassHint.innerHTML = `<span class="hint-label">下节课</span>: ${nextClass.name}`;
            nextClassHint.style.left = `calc(45% + ${miniCountdown.offsetWidth}px)`; // 定位在miniCountdown右侧
            nextClassHint.style.display = 'block';
            isHintShown = true;

            // 15秒后隐藏提示
            clearTimeout(hintTimer);
            hintTimer = setTimeout(() => {
                nextClassHint.classList.add('fadeOut'); // 淡出动画
                setTimeout(() => {
                    nextClassHint.style.display = 'none';
                    nextClassHint.classList.remove('fadeOut');
                    isHintShown = false; // 重置状态，允许下次触发
                }, 500); // 等待淡出动画完成
            }, 15000);
        }
    }

    if (scheduleData.currentHighlight.type === 'current') {
      if (isClassCountdown) {
        if (isClassHidden) { // 上课 并且开启了倒计时 并且 隐藏主体 -> 显示小窗口 
          countdownContainer.style.display = 'none'
          miniCountdown.style.display = 'block'
          miniCountdown.innerHTML = `<div class="currentClass">${currentFullName.innerText = scheduleData.currentHighlight.fullName}</div><div class="countdown" style="margin-left:5px">${scheduleData.currentHighlight.countdownText}</div>`
        } else { // 上课 并且开启了倒计时 并且 不隐藏主体 -> 正常计时
          countdownContainer.style.display = 'block'
          miniCountdown.style.display = 'none'
        }
      } else { // 上课 并且关闭了倒计时 -> 都不显示
        countdownContainer.style.display = 'none'
        miniCountdown.style.display = 'none'
      }
    }
    else { // 下课正常显示
      countdownContainer.style.display = 'block';
      miniCountdown.style.display = 'none'
    }
  }

   function setCountdownerPosition() {
    let highlightElement = document.getElementById('highlighted')
    let offset = {}
    if (scheduleData.currentHighlight.type === 'current') {
      offset = {
        x: highlightElement.offsetLeft - countdownContainer.offsetWidth / 2 + highlightElement.offsetWidth / 2,
        y: classContainer.offsetHeight
      }
    } else if (scheduleData.currentHighlight.type === 'upcoming') {
      if (scheduleData.currentHighlight.index != 0 && scheduleData.divider.indexOf((scheduleData.currentHighlight.index - 1)) != -1) {
        offset = {
          x: highlightElement.offsetLeft - countdownContainer.offsetWidth / 2 - Number(getComputedStyle(highlightElement).marginLeft.replace('px', '')) - getComputedStyle(root).getPropertyValue('--divider-width').replace('px', '') / 2 - getComputedStyle(root).getPropertyValue('--divider-margin').replace('px', ''),
          y: classContainer.offsetHeight
        }
      } else {
        offset = {
          x: highlightElement.offsetLeft - countdownContainer.offsetWidth / 2 - Number(getComputedStyle(highlightElement).marginLeft.replace('px', '')),
          y: classContainer.offsetHeight
        }
      }
    }
    if (scheduleData.currentHighlight.isEnd) {
      offset = {
        x: highlightElement.offsetLeft - countdownContainer.offsetWidth / 2 + highlightElement.offsetWidth + Number(getComputedStyle(highlightElement).marginLeft.replace('px', '')),
        y: classContainer.offsetHeight
      }
    }
  }

  function setSidebar() {
    let date = getCurrentEditedDate()
    let week = date.getDay()
    let data = scheduleConfig.daily_class[week]
    weekCH.innerText = data.Chinese
    weekEN.innerText = data.English
    if (scheduleConfig.countdown_target === 'hidden') {
      rightSidebar.style.display = 'none'
    } else {
      rightSidebar.style.display = 'block'
      countdownDays.innerText = Math.ceil(Math.abs(new Date(scheduleConfig.countdown_target) - date) / (1000 * 60 * 60 * 24))
    }
    leftSidebar.style.display = scheduleConfig.week_display ? 'block' : 'none'
  }

  function tick(reset = false) {
    scheduleData = getScheduleData();
    if (scheduleData.currentHighlight.fullName !== lastScheduleData.currentHighlight.fullName) {
        isHintShown = false;
        clearTimeout(hintTimer);
    }
    setCountdownerContent()
    if (JSON.stringify(scheduleData.scheduleArray) != JSON.stringify(lastScheduleData.scheduleArray) ||
      scheduleData.currentHighlight.index != lastScheduleData.currentHighlight.index ||
      scheduleData.currentHighlight.fullName != lastScheduleData.currentHighlight.fullName ||
      scheduleData.currentHighlight.type != lastScheduleData.currentHighlight.type || reset) {
      setScheduleClass()
      setCountdownerPosition()
      setSidebar()
      setBackgroundDisplay()
    }
    lastScheduleData = $.extend(true, {}, scheduleData)
  }


  // 获取下一节课信息
function getNextClassInfo() {
    const currentSchedule = getCurrentDaySchedule();
    const dayOfWeek = getCurrentEditedDay(getCurrentEditedDate());
    const timetable = scheduleConfig.daily_class[dayOfWeek].timetable;
    const dayTimetable = scheduleConfig.timetable[timetable];
    const timeKeys = Object.keys(dayTimetable);
    const currentTime = getCurrentTime();

    // 找到当前课程的下一个课程
    for (let i = 0; i < timeKeys.length; i++) {
        const timeRange = timeKeys[i];
        const [startTime, endTime] = timeRange.split('-');
        const classIndex = dayTimetable[timeRange];

        // 如果当前时间在本节课内，查找下一节
        if (typeof classIndex === 'number' && isClassCurrent(startTime, endTime, currentTime)) {
            // 从下一个时间段开始找下一节课
            for (let j = i + 1; j < timeKeys.length; j++) {
                const nextTimeRange = timeKeys[j];
                const nextClassIndex = dayTimetable[nextTimeRange];
                if (typeof nextClassIndex === 'number' && nextClassIndex < currentSchedule.length) {
                    const nextSubject = currentSchedule[nextClassIndex];
                    console.log("找到下节课：", nextSubject, nextTimeRange);
                    return {
                        name: scheduleConfig.subject_name[nextSubject], // 下节课全称
                        time: nextTimeRange.split('-')[0] // 下节课开始时间
                    };
                }
            }
            break;
        }
    }
    return null; // 没有下一节课
}


  let lastTickTime = new Date().getTime()
  setInterval(() => {
    if (new Date().getTime() - lastTickTime >= 1000) {
      lastTickTime = new Date().getTime()
      tick()
    }
  }, 20);

  for (key in scheduleConfig.css_style) {
    root.style.setProperty(key, scheduleConfig.css_style[key])
  }

  let timer = undefined
  window.addEventListener("mousemove", event => {
    if (event.target.className && event.target.className.indexOf('notIgnoreClick') == -1) {
      root.style.opacity = '0'
      clearTimeout(timer)
      timer = setTimeout(() => {
        root.style.opacity = '1'
      }, 7500);
    } else {
      clearTimeout(timer)
      root.style.opacity = '1'
    }
    if (event.target.className.indexOf('notIgnoreClick') == -1) {
      ipcRenderer.send('setIgnore', true)
    } else {
      ipcRenderer.send('setIgnore', false)
    }

  });
  ipcRenderer.send('setIgnore', true)

  function setScheduleDialog() {
    ipcRenderer.send('dialog', {
      reply: 'getSelectedClassIndex',
      options: {
        title: '临时更改课表',
        message: `请选择你要更改的课程序号`,
        buttons: scheduleData.scheduleArray.map((value, index) => { return `第 ${index + 1} 节: ${scheduleConfig.subject_name[value]}` }),
        cancelId: -1,
        defaultId: scheduleData.currentHighlight.index
      }
    })
  }

  ipcRenderer.on('getSelectedClassIndex', (e, arg) => {
    if (arg.index == -1) return
    let text = arg.arg.options.buttons[arg.index]
    let classes = Object.keys(scheduleConfig.subject_name).sort();
    ipcRenderer.send('dialog', {
      reply: 'getSelectedChangingClass',
      index: arg.index,
      classes: classes,
      options: {
        title: '更改课表',
        message: `将 第 ${arg.index + 1} 节 ${scheduleConfig.subject_name[scheduleData.scheduleArray[arg.index]]} 更改为:`,
        buttons: classes.map((value) => { return scheduleConfig.subject_name[value] }),
        cancelId: -1,
      }
    })
  })

  ipcRenderer.on('getSelectedChangingClass', (e, arg) => {
    if (arg.index == -1) return
    let index = arg.arg.index;
    let selectedClass = arg.arg.classes[arg.index];
    const date = getCurrentEditedDate();
    const dayOfWeek = getCurrentEditedDay(date);
    scheduleConfig.daily_class[dayOfWeek].classList[index] = selectedClass;
  })

  ipcRenderer.on('openSettingDialog', (e, arg) => {
    setScheduleDialog()
  })

  document.addEventListener("click", function (event) {
    if (event.target.className.indexOf('options') != -1) {
      ipcRenderer.send('pop')
    }
  });

  ipcRenderer.on('setWeekIndex', (e, arg) => {
    scheduleConfig = JSON.parse(JSON.stringify(_scheduleConfig))
    weekIndex = arg
    localStorage.setItem('weekIndex', weekIndex.toString())
  })

  ipcRenderer.on('getWeekIndex', (e, arg) => {
    let index = localStorage.getItem('weekIndex');
    ipcRenderer.send('getWeekIndex', index === null ? 0 : Number(index))
  })

  ipcRenderer.on('getTimeOffset', (e, arg) => {
    let offset = localStorage.getItem('timeOffset');
    ipcRenderer.send('getTimeOffset', offset === null ? 0 : Number(offset))
  })

  ipcRenderer.on('setTimeOffset', (e, arg) => {
    timeOffset = arg
    localStorage.setItem('timeOffset', arg.toString())
  })

  ipcRenderer.on('ClassCountdown', (e, arg) => {
    isClassCountdown = arg
    tick(reset = true)
  })

  ipcRenderer.on('ClassHidden', (e, arg) => {
    isClassHidden = arg
    tick(reset = true)
  })

  ipcRenderer.on('setDayOffset', (e, arg) => {
    ipcRenderer.send('dialog', {
      reply: 'getDayOffset',
      options: {
        title: '切换日程',
        message: `将今日使用课表日程设置为本周的星期几：`,
        buttons: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '重置至当前日期'],
        cancelId: -1,
      }
    })
  })

  ipcRenderer.on('getDayOffset', (e, arg) => {
    if (arg.index == -1) return
    if (arg.index <= 6) {
      localStorage.setItem('dayOffset', arg.index.toString())
      localStorage.setItem('setDayOffsetLastDay', new Date().getDay().toString())
      dayOffset = arg.index
      setDayOffsetLastDay = new Date().getDay()
      return
    }
    localStorage.setItem('dayOffset', '-1')
    localStorage.setItem('setDayOffsetLastDay', '-1')
    dayOffset = -1
    setDayOffsetLastDay = -1
  })
</script>

</html>